const utils=require('utils.js')
Page({
  data:{
    meters:0,
    seconds:0,
    latitude:0,
    longitude:0,
    running:false,
    interval:1000,
    markers:[]
  },
  curLocation(){
    wx.getLocation({
      type:'gcj02'
    }) .then(res=>{
      console.log(res)
      let{latitude,longitude} = res
      this.setData({
        latitude,longitude
      })
    })
  },
  onLoad(){
    this.curLocation()
    setInterval(this.record,this.data.interval)
  },
  test(){
    let meters= utils.getDistance(23.383101,113.449479,23.38703,113.446121)
    this.setData({
      meters
    })
  },
  run(){
    this.setData({
      running:!this.data.running
    })
  },
  record(){
    if(!this.data.running){
      return
    }
    this.setData({
      seconds:this.data.seconds + this.data.interval/1000
    })
    wx.getLocation({
      type:'gcj02'
    }).then(res=>{
      let newMarker={
        latitude:res.latitude,
        longitude:res.longitude,
        iconPath:'redPoint.png',
        width:10,
        height:10
      }
      let pace = 0
      let markers = this.data.markers
      if(this.data.markers.length>0){
        let lastMarker = this.data.markers.slice(-1)[0]
        console.log(lastMarker)
        console.log(newMarker)
        pace = utils.getDistance(lastMarker.latitude,lastMarker.longitude,newMarker.latitude,newMarker.longitude)
        if(pace>15){
          markers.push(newMarker)
        }else{
          pace=0
        }
      }else{
        markers.push(newMarker)
      }
      this.setData({
        latitude:res.latitude,
        longitude:res.longitude,
        markers,
        meters:this.data.meters + pace
      })
    })
  },
  clear(){
    this.setData({
      markers:[],
      meters:0,
      seconds:0
    })
  }
})